<?php
namespace Modules\Common\General\Upload;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Modules\Common\General\Upload\Exceptions\FileNotExistException;
use Modules\Common\General\Upload\Exceptions\PathNotExistException;
use Modules\Common\Models\File;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;
use Modules\Common\General\Upload\Exceptions\FileRepeatException;
use Aliyunoss\AliyunOSS;

class UploadController
{
    protected $ossService;
    protected $tags = [
        'ebook-upload' => 'ebook-upload',
        // ...更多上传业务
    ];
    public function __construct()
    {
        $this->ossService = new AliyunOSS();
        $this->cdndomain = config('aliyun.oss.cdnDomain');
    }

    /**
     * 系统通用上传接口
     * @Route(path=/api/upload/{tag} method=post)
     */
    public function upload(string $tag, Request $request)
    {
        set_time_limit(0);

        if (!array_key_exists($tag, $this->tags)) {
            throw new PathNotExistException('URL 路径不存在！');
        }

        $file = $request->file('file');
        if (!$file) {
            throw new FileNotExistException('上传文件未传！');
        }

        $storeName = Str::random(20) . '.' . $file->getClientOriginalExtension();
        $objectKey = $this->path($tag) . '/' . $storeName;

        try {
            $filePath = $file->getPathName();
            $url = $this->ossService->upload($filePath, $objectKey);
            // 返回完整的访问 URL
            $entire_url =  $this->cdndomain.'/' . $objectKey; // 使用 CDN 域名
            // 存储文件记录到数据库...
            $md5 = md5_file($file->getRealPath());
            $isRepeat = File::where(['tag' => $tag, 'md5' => $md5])->where('used', Database::BOOL_TRUE)->exists();
            $eidDefault = auth('api')->user()->eid; 
            $sidDefault = auth('api')->user()->sid;
            $record = File::create([
                'tag' => $tag,
                'eid'=>$eidDefault,
                'sid'=>$sidDefault,
                'file_name' => $file->getClientOriginalName(),
                'size' => $file->getSize(),
                'path' => $entire_url,
                'ip' => $request->getClientIp(),
                'removed' => Database::BOOL_FALSE,
                'md5' => $md5,
                'used' => $isRepeat ? Database::BOOL_TRUE : Database::BOOL_FALSE
            ]);

            if ($isRepeat) {
                throw new FileRepeatException('该文件已存在，请上传新的文件');
            }

            return Api::success(['fileId' => $record->id, 'path' => $entire_url], '上传成功');
        } catch (\Exception $e) {
            throw new \Exception('文件上传失败: ' . $e->getMessage());
        }
    }

    private function path($tag)
    {
        return $this->tags[$tag] . '/' . date('Y-m-d');
    }
}